<template lang="pug">
  v-container
    v-card
      v-toolbar(color="purple darken-4" dark dense)
        v-toolbar-title 基本信息
        v-spacer
        v-toolbar-items
          v-btn(text @click="back") 返回
          v-btn(text @click="reset") 重置
          v-btn(text @click="save") 保存
      v-card-text
        v-form(ref="form")
          v-container
            v-row
              v-col(cols="12")
                v-text-field(type="text" :label="Lang['name']" v-model="feeFormulaClone.name" :rules="[rules.required]")
              v-col(cols="12")
                v-textarea(type="text" :label="Lang['description']" v-model="feeFormulaClone.description")
              v-col(cols="12")
                v-text-field(type="text" :label="Lang['criteria']" v-model="feeFormulaClone.criteria" :rules="[rules.required]" :messages="criteriaHelpeMsg")
                  template(v-slot:message)
                    div(v-for="msg in criteriaHelpeMsg") {{msg}}
              v-col(cols="12")
                v-text-field(type="text" :label="Lang['formula']" v-model="feeFormulaClone.formula" :rules="[rules.freeFormula]" :messages="formulaHelpeMsg" :error-messages="formulaErrorMsg")
                  template(v-slot:message)
                    div(v-for="msg in formulaHelpeMsg") {{msg}}
              v-col(cols="12")
                v-card
                  v-card-title 模拟计算
                  v-card-text
                    v-container
                      v-row
                        v-col(cols="3")
                          v-text-field(type="number" v-model="play.price" label="资产市场价格")
                        v-col(cols="3")
                          v-text-field(type="number" v-model="play.duration" label="租赁天数")
                        v-col(cols="3")
                          v-text-field(type="number" v-model="play.discount" label="折扣")
                        v-col(cols="3")
                          v-text-field(type="number" v-model="playResult" label="计算结果" readonly=true)
</template>

<script lang="ts">
  import Vue, {VueConstructor} from 'vue'
  import EditFormMixin from '@/components/mixins/EditFormMixin'
  import VDateField from '@/components/widgets/form_fields/VDateField'
  import {FeeFormula, FeeFormulaLang} from '@/store/modules/types/FeeFormula'
  import {mapActions, mapMutations, mapState} from 'vuex'
  import country from '@/api/country'
  import {AxiosResponse} from 'axios'


  export default (Vue as VueConstructor<Vue & {
    $refs: {}
  }>).extend({
    name: 'fee_formula_form',
    components: { VDateField },
    mixins: [EditFormMixin],
    methods: {
      ...mapActions('feeFormula', ['createOrUpdate']),
      ...mapMutations('feeFormula', ['setActive']),
      save(){
        this.$loading('保存中...')
        this.createOrUpdate().then((response: AxiosResponse) => {
          let { feeFormula }: { feeFormula: FeeFormula } = response.data
          this.setActive(feeFormula)
        }).then(() => {
          this.$msgBox('保存成功')
        }).finally(()=>{
          this.$loading.close()
        })
      },
      calc(){
        let f = this.feeFormulaClone.formula
        let _evalText = ['price', 'duration', 'discount'].reduce((acc, key)=>{
          let reg = new RegExp(`\{${key}\}`, 'g')
          acc = acc.replace(reg, this.play[key])
          return acc
        }, f)
        try{
          let _result = eval(_evalText)
          this.playResult = _result
          this.formulaErrorMsg = null
        }catch(error){
          this.formulaErrorMsg = "公式错误"
        }
      }
    },
    computed: {
      ...mapState('feeFormula', ['feeFormulaClone'])
    },
    watch: {
      "feeFormulaClone.formula": {
        handler(){
          this.calc()
        }
      },
      play: {
        handler(val){
          this.calc()
        },
        deep: true
      }
    },
    data() {
      return {
        play: {
          price: 100,
          duration: 20,
          discount: 0.7,
        },
        playResult: 0,
        formulaErrorMsg: null,
        Lang: FeeFormulaLang,
        criteriaHelpeMsg: [
          'and : 并且',
          'or : 或者',
          'name : 资产名称',
          'duration : 租赁天数',
          'category: 一级分类',
          'subCategory: 二级级分类',
          'price: 资产市场价格',
          '示例：name = 资产名称 and duration > 10天 and duration < 2月 and category = 相机'
        ],
        formulaHelpeMsg: [
          '{price} : 资产市场价格',
          '{discount} : 订单折扣',
          '{duration} : 租赁天数',
          '示例：({duration} / 100) * {price} * {discount} + 200 '
        ],

      }
    }
  })
</script>